package com.xiaoshuidi.cloud.module.member.api.coupon;

import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.module.member.api.coupon.vo.*;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.CouponCustomerPCForm;
import com.xiaoshuidi.cloud.module.member.enums.coupon.CouponTypeEnum;
import com.xiaoshuidi.cloud.module.member.pojo.coupon.CouponEntity;
import com.xiaoshuidi.cloud.module.member.service.coupon.CouponCustomerService;
import com.xiaoshuidi.cloud.module.member.service.coupon.CouponService;
import com.xiaoshuidi.cloud.module.member.service.user.MemberUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.xiaoshuidi.cloud.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.xiaoshuidi.cloud.module.member.enums.ErrorCodeConstants.PARAM_MISS;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class CouponApiImpl implements CouponApi {

    @Resource
    CouponService couponService;
    @Resource
    CouponCustomerService couponCustomerService;
    @Resource
    MemberUserService memberUserService;

    @Override
    public void sendCouponByBusiness(SendCouponByBusinessVo vo) {
        List<CouponEntity> coupons = couponService.getAvailableCouponsByStoreId(vo.getStoreId(), vo.getCouponType());
        if (CollectionUtils.isEmpty(coupons)) {
            return;
        }
        List<CouponEntity> sends = new ArrayList<>();
        //优惠券活动筛选
        for (CouponEntity item : coupons) {
            //预定优惠
            if (CouponTypeEnum.RESERVATION_DISCOUNT.getNum().equals(item.getCouponType())) {
                if (vo.getBookDate() == null || vo.getDeposit() == null || vo.getSignDate() == null) {
                    throw exception(PARAM_MISS);
                }
                //预定日期区间、金额、签约日期区间
                if (item.getScheduledStartTime().after(vo.getBookDate()) || item.getExpirationEndTime().before(vo.getBookDate())
                        || item.getScheduledAmount().compareTo(vo.getDeposit()) > 1
                        || item.getSigningStartTime().after(vo.getSignDate()) || item.getSigningEndTime().before(vo.getSignDate())) {
                    continue;
                } else {
                    sends.add(item);
                }
            }
            //老带新、新签优惠
            if (CouponTypeEnum.OLD_WITH_NEW_DISCOUNT.getNum().equals(item.getCouponType())
                    || CouponTypeEnum.NEW_SIGNING_DISCOUNT.getNum().equals(item.getCouponType())) {
                if (vo.getMonth() == null || vo.getSignDate() == null
                        || (CouponTypeEnum.OLD_WITH_NEW_DISCOUNT.getNum().equals(item.getCouponType()) && StringUtils.isBlank(vo.getOldPhone()))) {
                    throw exception(PARAM_MISS);
                }
                //签约日期区间、租期区间
                if (item.getSigningStartTime().after(vo.getSignDate()) || item.getSigningEndTime().before(vo.getSignDate())
                        || item.getMiniLeaseMonth() > vo.getMonth() || item.getMaxLeaseMonth() < vo.getMonth()) {
                } else {
                    sends.add(item);
                }
            }
        }
        //符合的优惠券活动发券
        if (!sends.isEmpty()) {
            String phone = memberUserService.getUser(vo.getTenantUserId()).getMobile();
            for (CouponEntity item : sends) {
                CouponCustomerPCForm form = new CouponCustomerPCForm();
                form.setCouponId(item.getId());
                form.setUserPhone(phone);
                form.setOldUserPhone(vo.getOldPhone());
                form.setRemarks("业务自动发券");
                if (CouponTypeEnum.NEW_SIGNING_DISCOUNT.getNum().equals(item.getCouponType())) {
                    form.setCouponNum(vo.getMonth().longValue());
                }
                form.setIssuingMethod(0);
                couponService.sendCustomerCoupon(form);
            }
        }
    }

//    @Override
//    public CommonResult<CouponCheckRespVo> checkBillCoupons(CouponCheckReqVo reqVo) {
//        CouponCheckRespVo result = new CouponCheckRespVo();
//        List<CouponSimpleInfoVo> availables = new ArrayList<>();
//        List<CouponSimpleInfoVo> disables = new ArrayList<>();
//        Map<Integer, List<Long>> useOverlays = new HashMap<>();
//        //当前用户优惠券
//        List<CouponCustomerInfoVo> coupons = couponCustomerService.queryByIds(reqVo.getCouponIds());
//        Date now = new Date();
//        for (CouponCustomerInfoVo item : coupons) {
//            CouponSimpleInfoVo vo = new CouponSimpleInfoVo(item);
//            if (item.getCouponType().intValue() == CouponTypeEnum.RESERVATION_DISCOUNT.getNum().intValue()) {
//                //券类型是预定，非本人、非活动门店、非使用时间优惠券排除，签约日期不在可使用的签约日期范围内
//                if (!reqVo.getTenantUserId().equals(item.getUserId())
//                        || (item.getActivityStore() != -1 && !item.getActivityStore().equals(reqVo.getStoreId()))
//                        || (item.getExpirationStartTime().after(now) || item.getExpirationEndTime().before(now))
//                        || (item.getSigningStartTime().after(now) || item.getSigningEndTime().before(now))) {
//                    disables.add(vo);
//                    continue;
//                }
//
//            } else if (item.getCouponType().intValue() == CouponTypeEnum.OLD_WITH_NEW_DISCOUNT.getNum().intValue()
//                    || item.getCouponType().intValue() == CouponTypeEnum.NEW_SIGNING_DISCOUNT.getNum().intValue()) {
//                //券类型是老带新或者新签约，非本人、非活动门店、非使用时间优惠券排除，签约日期不在可使用的签约日期范围内,租赁月份在区间内
//                if (!reqVo.getTenantUserId().equals(item.getUserId())
//                        || (item.getActivityStore() != -1 && !item.getActivityStore().equals(reqVo.getStoreId()))
//                        || (item.getExpirationStartTime().after(now) || item.getExpirationEndTime().before(now))
//                        || (item.getSigningStartTime().after(now) || item.getSigningEndTime().before(now))
//                        || (item.getMiniLeaseMonth() > reqVo.getLeaseMonth() && reqVo.getLeaseMonth() > item.getMaxLeaseMonth())) {
//                    disables.add(vo);
//                    continue;
//                }
//            } else if (item.getCouponType().intValue() == CouponTypeEnum.INTERNAL_EMPLOYEE_DISCOUNT.getNum().intValue()) {
//                //券类型是内部员工，非本人、非使用时间优惠券排除
//                if (!reqVo.getTenantUserId().equals(item.getUserId())
//                        || (item.getExpirationStartTime().after(now) || item.getExpirationEndTime().before(now))) {
//                    disables.add(vo);
//                    continue;
//                }
//            } else if (item.getCouponType().intValue() == CouponTypeEnum.OTHER_DISCOUNT.getNum().intValue()) {
//                //券类型是其他优惠，非本人、非活动门店、非使用时间优惠券排除
//                if (!reqVo.getTenantUserId().equals(item.getUserId())
//                        || (item.getActivityStore() != -1 && !item.getActivityStore().equals(reqVo.getStoreId()))
//                        || (item.getExpirationStartTime().after(now) || item.getExpirationEndTime().before(now))) {
//                    disables.add(vo);
//                    continue;
//                }
//            }
//
//
//            //叠加使用处理
//            //同一优惠类型
//            if (item.getCouponUseOverlay().contains("1")) {
//                this.setUseOverlay(item.getCouponType(), useOverlays, item.getId());
//            }
//            //跨优惠类型
//            if (item.getCouponUseOverlay().contains("2")) {
//                this.setUseOverlay(-1, useOverlays, item.getId());
//            }
//
//        }
//        result.setAvailables(availables);
//        result.setDisables(disables);
//        result.setUseOverlays(useOverlays.values().stream().collect(Collectors.toList()));
//        return CommonResult.success(result);
//    }

    private Map<Integer, List<Long>> setUseOverlay(Integer couponType, Map<Integer, List<Long>> map, Long couponId) {
        if (map.containsKey(couponType)) {
            List<Long> temp = map.get(couponType);
            temp.add(couponId);
            map.put(couponType, temp);
        } else {
            map.put(couponType, Arrays.asList(couponId));
        }
        return map;
    }

    @Override
    public CommonResult<List<CouponUpdateReturn>> couponAddLock(CouponLockVo couponLockVo) {
        List<CouponUpdateReturn> list = couponCustomerService.couponAddLock(couponLockVo);
        return CommonResult.success(list);
    }

    @Override
    public CommonResult<Boolean> couponUntieLock(CouponUnLockVo couponUnLockVo) {
        Boolean aBoolean = couponCustomerService.couponUntieLock(couponUnLockVo);
        return CommonResult.success(aBoolean);
    }

    @Override
    public CommonResult<Boolean> updateCoupon(List<CouponUpdateVo> couponUpdateVos) {
        Boolean aBoolean = couponCustomerService.updateCoupon(couponUpdateVos);
        return CommonResult.success(aBoolean);
    }

    @Override
    public CommonResult<CouponReturn> couponReturn(CouponLockVo couponLockVo) {
        CouponReturn couponReturn = couponCustomerService.couponReturn(couponLockVo);
        return CommonResult.success(couponReturn);
    }


}
